/**
 * @description 用户
 * @author MaoXiangDong
 * @version 2021/3/15
 * @Email: 1257538859@qq.com
 * @WeChat: 19908853414
 */
import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/cookie'
import router, { resetRouter } from '@/router'
const state = {
  userInfo: sessionStorage.getItem('userInfo') ? JSON.parse(sessionStorage.getItem('userInfo')) : {},
  token: getToken(),
  rules: [] // 权限id集合
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_RULES: (state, rules) => {
    state.rules = rules
  }
}

const actions = {
// 登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ userName: username.trim(), passWord: password }).then(response => {
        const { data } = response
        console.log(data);
        commit('SET_TOKEN', data.token)
        commit('SET_USERINFO', data.userInfo)
        sessionStorage.setItem('userInfo', JSON.stringify(data.userInfo))
        setToken('', data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve) => {
      const userInfo = state.userInfo
      const { rules } = userInfo
      commit('SET_RULES', rules)
      resolve(userInfo)
    })
  },

  // 退出登录
  // eslint-disable-next-line no-unused-vars
  logout({ commit, state, dispatch }) {
    return new Promise(async(resolve) => {
      // 重置访问的视图和缓存的视图
      dispatch('page/delAllViews', null, { root: true })
      await dispatch('resetToken') // 清除 token
      resolve()
      logout(state.token)
    })
  },

  // 清除 token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_RULES', [])
      commit('SET_USERINFO', {})
      sessionStorage.removeItem('userInfo')
      removeToken()
      // 重置路由
      resetRouter()
      resolve()
    })
  },

  // 动态修改权限
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'
      commit('SET_TOKEN', token)
      setToken('', token)
      const { rules } = await dispatch('getInfo')
      // 重置路由
      resetRouter()
      const accessRoutes = await dispatch('permission/generateRoutes', rules, { root: true })
      router.addRoute(accessRoutes)
      dispatch('page/delAllViews', null, { root: true })
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
